package com.utils;


import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.util.DisplayMetrics;

import com.entity.User;
import com.receive.SMSReceiverSend;
import com.show.api.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.user;
import static com.utils.ChatClient.userInfo;

public class Constants {
    public static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    //银行电话号码
    public static String MOBILE_BOB = "";
    public static String MOBILE_BOB_86 = "";
    //银行转账缓存第一条读取信息
    public static String CacheInfo = "";
    //银行转账上报结果正确的缓存信息
    public static String SendResultCacheInfo = "";
    //银行二维码上报时间的缓存
    public static String QRCodeUpdateTime = "";
    //接收状态
    public static boolean ISCHECKED = true;
    //短信验证码
    public static String CODE = "";
    //短信内容
    public static String SMSMESSAGE = "";
    // 短信序列号
    public static String TV_TIPS = "";

    public static int SMSTYPE = 0;
    //账单银行名
    public static String orderBankName = "";
    //是否上报
    public static boolean isReport = true;
    public static boolean notReport = false;


    //USB
    public final static String ACTION_USB = "android.hardware.usb.action.USB_STATE";
    public final static String ACTION_DEVICE_PERMISSION = "com.linc.USB_PERMISSION";
    public static boolean STATE_USB = true;
    //设备终端号
    public static int PROT = 0000;

    //订单状态
    public static int STATE_SUCCESS = 0;//状态:成功
    public static int STATE_FAIL = 1;//状态:失败
    public static int STATE_PROCESS = 4;//状态:待处理
    public static int STATE_TO_BE_CONFIRMED = 6;//状态:待确认

    public static String getBank(String bankName, String bankCode) {
        String temp = bankName;
        switch (bankName) {
            case "中国进出口银行":
                temp = "中国进出口银行";
                break;
            case "中国农业发展银行":
                temp = "中国农业发展银行";
                break;
            case "国家开发银行":
                temp = "国家开发银行";
                break;
            case "中国工商银行":
                temp = "中国工商银行";
                break;
            case "中国农业银行":
                temp = "中国农业银行";
                break;
            case "中国银行":
                temp = "中国银行";
                break;
            case "中国建设银行":
                if (bankCode.equals("CEB")) {
                    temp = "建设银行";
                } else {
                    temp = "中国建设银行";
                }
                break;
            case "交通银行":
                temp = "交通银行";
                break;
            case "中信银行":
                temp = "中信银行";
                break;
            case "中国光大银行":
                if (!"BOC".equals(bankCode) && !"CEB".equals(bankCode) && !"CMBC".equals(bankCode) && !"CZB".equals(bankCode)
                        && !"PSBC".equals(bankCode) && !"CCB".equals(bankCode) && !"ICBC".equals(bankCode)) {
                    temp = "光大银行";
                }
                break;
            case "华夏银行":
                temp = "华夏银行";
                break;
            case "广发银行":
                temp = "广发银行";
                break;
            case "深圳发展银行":
                temp = "深圳发展银行";
                break;
            case "招商银行":
                temp = "招商银行";
                break;
            case "上海浦东发展银行":
                if ("ICBC".equals(bankCode) || "CGB".equals(bankCode) || "CMB".equals(bankCode) || "PSBC".equals(bankCode) ||
                        "CCB".equals(bankCode)) {
                    temp = "上海浦东发展银行";
                } else if ("BCM".equals(bankCode) || "SPDB".equals(bankCode) || "CEB".equals(bankCode) || "CIB".equals
                        (bankCode) || "CZB".equals(bankCode) || "SPDB".equals(bankCode)) {
                    temp = "浦发银行";
                } else {
                    temp = "浦东发展银行";
                }
                break;
            case "浦发银行":
                if ("ICBC".equals(bankCode) || "BOC".equals(bankCode) || "CMB".equals(bankCode)) {
                    temp = "上海浦东发展银行";
                } else if ("BCM".equals(bankCode) || "SPDB".equals(bankCode) || "CIB".equals(bankCode)) {
                    temp = "浦发银行";
                } else {
                    temp = "浦东发展银行";
                }
                break;
            case "浦东发展银行":
                if ("ICBC".equals(bankCode) || "BOC".equals(bankCode) || "CMB".equals(bankCode) || "PSBC".equals(bankCode)) {
                    temp = "上海浦东发展银行";
                } else if ("BCM".equals(bankCode) || "SPDB".equals(bankCode)) {
                    temp = "浦发银行";
                } else {
                    /***农行***/
                    temp = "浦东发展银行";
                }
                break;
            case "浦东发展":
                if ("ICBC".equals(bankCode) || "BOC".equals(bankCode) || "CMB".equals(bankCode)) {
                    temp = "上海浦东发展银行";
                } else if ("BCM".equals(bankCode) || "SPDB".equals(bankCode)) {
                    temp = "浦发银行";
                } else {
                    temp = "浦东发展银行";
                }
                break;
            case "中国民生银行":
                if (!"ABC".equals(bankCode) && !"BOC".equals(bankCode) && !"CMBC".equals(bankCode) && !"CCB".equals(bankCode)
                        && !"ICBC".equals(bankCode)) {
                    temp = "民生银行";
                }
                break;
            case "兴业银行":
                temp = "兴业银行";
                break;
            case "恒丰银行":
                temp = "恒丰银行";
                break;
            case "浙商银行":
                temp = "浙商银行";
                break;
            case "渤海银行":
                temp = "渤海银行";
                break;
            case "中国邮政储蓄银行":
                if ("ICBC".equals(bankCode) || "CIB".equals(bankCode)) {
                    temp = "邮政储汇";
                } else if ("SPDB".equals(bankCode) || "SPDB".equals(bankCode)) {
                    temp = "邮储银行";
                } else if ("CGB".equals(bankCode) || "CMB".equals(bankCode) || "CMBC".equals(bankCode) || "ABC".equals(bankCode)
                        || "PSBC".equals(bankCode) || "CCB".equals(bankCode) || "CZB".equals(bankCode)) {
                    temp = "中国邮政储蓄银行";
                } else if (!"BOC".equals(bankCode)) {
                    temp = "邮政储蓄银行";
                }
                break;
            case "邮政储汇":
                if ("ICBC".equals(bankCode)) {
                    temp = "邮政储汇";
                } else if ("SPDB".equals(bankCode)) {
                    temp = "邮储银行";
                } else if ("ABC".equals(bankCode)) {
                    temp = "中国邮政储蓄银行";
                } else {
                    temp = "邮政储蓄银行";
                }
                break;
            case "邮储银行":
                if ("ICBC".equals(bankCode)) {
                    temp = "邮政储汇";
                } else if ("SPDB".equals(bankCode)) {
                    temp = "邮储银行";
                } else if ("ABC".equals(bankCode)) {
                    temp = "中国邮政储蓄银行";
                } else {
                    temp = "邮政储蓄银行";
                }
                break;
            case "邮政储蓄银行":
                if ("ICBC".equals(bankCode)) {
                    temp = "邮政储汇";
                } else if ("SPDB".equals(bankCode)) {
                    temp = "邮储银行";
                } else if ("ABC".equals(bankCode)) {
                    temp = "中国邮政储蓄银行";
                } else {
                    temp = "邮政储蓄银行";
                }
                break;
            case "平安银行":
                temp = "平安银行";
                break;
            case "北京银行":
                temp = "北京银行";
                break;
            case "上海银行":
                temp = "上海银行";
                break;
            case "厦门银行":
                temp = "厦门银行";
                break;
            case "河南省农村信用社":
                temp = "河南省";
                break;
            default:
                temp = bankName;
                break;
        }
        return temp;
    }

    public static int getStr(String str) {
        LogToFile.d("====成功标识====", "成功标识:" + str);
        int status = 1;
        if (StringUtils.isEmpty(str)) {
            return status;
        }
        if (str.contains("处理中") ||
                str.contains("交易处理中") ||
                str.contains("成功") ||
                str.contains("转账成功") ||
                str.contains("转账成功!") ||
                str.contains("转账已受理") ||
                str.contains("转账提交成功") ||
                str.contains("已实时到账") ||
                str.contains("恭喜您,转账成功!") ||
                str.contains("转账提交成功") ||
                str.contains("交易受理") ||
                str.contains("交易成功") ||
                str.contains("交易已受理") ||
                str.contains("非工作时间段大额预约处理") ||
                str.contains("预约汇款,请确认") ||
                str.contains("跨行汇款受理成功") ||
                str.contains("行内汇款受理成功") ||
                str.contains("交易已成功受理!")
                ) {
            System.out.println("包含");
            status = 0;//您的预约汇款交易受理成功，请查询收款账户的到账情况，并确认交易结果。
        } else if (str.contains("没有查找到记录")) {
            LogToFile.d("=====status为4====", "=====status为4===");
            status = 4;//状态待确认
        } else if (str.contains("交易处理中") || str.contains("预约汇款,请确认") || str.contains("未检测到转账结果") || str.contains("没有查找到记录")) {
            LogToFile.d("=====status为6====", "=====status为6===");
            status = 6;//状态待确认
        } else {
            System.out.println("不包含");
            status = 1;//状态失败
        }
        return status;
    }

    public static String getPayName(int prot) {
        String temp = "";
        switch (prot) {
            case 6526:
                temp = "BOB";
                break;
            case 6588:
                temp = "ICBC";
                break;
            case 6528:
                temp = "SPDB";
                break;
            case 6568:
                temp = "CMBC";
                break;
            case 6580:
                temp = "PSBC";
                break;
            case 6533:
                temp = "CCB";
                break;
            case 6561:
                temp = "CIB";
                break;
            case 6599:
                temp = "ABC";
                break;
            case 6559:
                temp = "BCM";
                break;
            case 6555:
                temp = "CMB";
                break;
            case 6577:
                temp = "HXB";
                break;
        }
        return temp;
    }

    /**
     * 将 s 进行 BASE64 编码
     *
     * @return String
     * @author lifq
     * @date 2015-3-4 上午09:24:02
     */
    public static String encode(String s) {
        if (s == null)
            return null;
        String res = "";
        try {
            res = new sun.misc.BASE64Encoder().encode(s.getBytes("GBK"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 获取执行方法名
     *
     * @param i 第几位
     * @return 方法名
     */
    public static String getMethod(int i) {
        Exception exception = new Exception();
        StackTraceElement[] trace = exception.getStackTrace();
        String method = trace[i].getMethodName();
        return method;
    }

    /**
     * 银行脚本启动
     *
     * @param mDevice  设备页面
     * @param bankName 银行名称
     * @throws UiObjectNotFoundException UI异常
     */
    public static void scriptToStart(UiDevice mDevice, String bankName) throws UiObjectNotFoundException {
        LogToFile.showLog(orderBankName, "scriptToStart inter");
        if(!android.os.Build.MODEL.contains("2017M27A")) {
            UIUtils.initServicePermission(mDevice);
        }
        // 为了防止在点击银行之前有不可确定的对话框覆盖5
        sleep(ChatClient.overtime_2);
        mDevice.pressHome();
        LogToFile.showLog(orderBankName, "点击home键");
        sleep(ChatClient.overtime_1);
        mDevice.pressHome();
        LogToFile.showLog(orderBankName, "点击home键");
        Constants.tryingToReadAccountInformation(mDevice, bankName);
        //启动银行app
         while(true){
             UiObject x = mDevice.findObject(new UiSelector().text(bankName));
             if (x.exists()) {
                 LogToFile.showLog(orderBankName, "点击启动银行");
                 x.click();
                 break;
             } else {
                 LogToFile.showLog(orderBankName, "descriptionContains==点击启动银行");
                 x = mDevice.findObject(new UiSelector().descriptionContains(bankName));
                 if(x.exists()){
                     x.click();
                     break;
                 }
             }
             sleep(ChatClient.overtime_1);
         }
    }

    /**
     * 动态注册短信广播监听
     *
     * @param context        文本
     * @param sMSReceiverSen 短信广播
     * @param bankCall       银行电话
     */
    public static void registerSMSMonitor(Context context, SMSReceiverSend sMSReceiverSen, String bankCall) {
        //动态注册短信广播
        Constants.MOBILE_BOB = bankCall;
        Constants.MOBILE_BOB_86 = "+86" + bankCall;
        Constants.CODE = "";
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.SMS_ACTION);
        filter.addAction("net.blogjava.mobile.SMSto");
        // 设置优先级 不然监听不到短信
        filter.setPriority(1000);
        context.registerReceiver(sMSReceiverSen, filter);
        Intent intent = new Intent();
        intent.setAction("com.tiantian.SEND_TO");
        context.sendBroadcast(intent);
    }

    /**
     * 获取屏幕宽度、版本号及机型
     *
     * @param context       文本
     * @param orderBankName 银行名称
     * @return 屏幕宽度
     */
    public static int getScreenHeight(Context context, String orderBankName) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        // 手机屏幕宽度
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        LogToFile.d(orderBankName, "屏幕宽度：" + screenWidth + ",screenHeight==" + screenHeight);
        getsTheModelAndVersionNumberAndVersionName(context, orderBankName);
        return screenHeight;
    }

    /**
     * 获取型号和版本号以及版本名称
     *
     * @param context
     * @param bankName
     */
    public static void getsTheModelAndVersionNumberAndVersionName(Context context, String bankName) {
        String carrier = android.os.Build.MODEL;
        LogToFile.showLog(bankName, carrier);
        LogToFile.showLog(bankName, "Android版本：" + android.os.Build.VERSION.RELEASE);
        LogToFile.showLog(bankName, "ZUI版本：" + android.os.Build.VERSION.INCREMENTAL);
        LogToFile.showLog(bankName, "脚本版本号：" + Constants.getVersionCode(context));
        LogToFile.showLog(bankName, "脚本版本名称：" + Constants.getVersionName(context));
    }

    /**
     * A-MOB正在尝试读取帐号信息
     *
     * @param mDevice       UiDevice
     * @param orderBankName 银行名称
     */
    public static void tryingToReadAccountInformation(UiDevice mDevice, String orderBankName) throws
            UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                LogToFile.showLog(orderBankName, "未检测到A-MOB正在尝试读取帐号信息对话框");
                return;
            }
            UiObject allow = mDevice.findObject(new UiSelector().text("允许").resourceId("com.android" +
                    ".packageinstaller:id/permission_allow_button"));
            if (allow.exists()) {
                //进入转账
                LogToFile.d("========", "点击A-MOB正在尝试读取帐号信息对话框的允许");
                allow.click();
                break;
            }
        }
    }

    /**
     * 获取账号信息
     *
     * @param method 调用的方法名
     */
    public static void getAccountInformation(String method) {
        ImageView.saveImg("");
        sleep(1000);
        //连接服务端
        ChatClient.start();
        //获取账号信息
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(method, ChatClient.errorStr);
                return;
            }
            if (StringUtils.isEmpty(userInfo)) {
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_GET_BANK_LOGIN_INFO_P + "'}</YZF>");
                sleep(ChatClient.overtime_3);
            } else {
                user = new User();
                String[] res = userInfo.split(" ");
                user.setUserName(res[0]);
                user.setPwd(res[1]);
                user.setBankpwd(res[2]);
                user.setUsbPayPwd(res[3]);
                user.setUseType(res[4]);
                user.setBankId(res[5]);
                break;
            }
        }
        sleep(4000);
    }

    public static int getVersionCode(Context context) {
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取包信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //返回版本号
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getVersionName(Context context) {
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取包信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //返回版本号
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 计算余额变化
     *
     * @param bankName       银行卡号
     * @param saveTheAmount  保存的金额
     * @param realTimeAmount 获取的实时金额
     * @param orderAmount    查账订单金额
     * @return 4：为金额没变化，在重新转账；0：为金额有变化，保存的金额减获取的实时金额减上一个订单金额=0上报成功；1：为金额有变化，不等于0上失败（待确认）
     */
    public static String changeInAmount(String bankName, String saveTheAmount, String realTimeAmount, String orderAmount) {
        String statusCode = "1";
        LogToFile.d(bankName, "保存的金额 ===" + saveTheAmount);
        LogToFile.d(bankName, "获取的实时金额 ===" + realTimeAmount);
        LogToFile.d(bankName, "查账订单金额 ===" + orderAmount);

        if (sub(saveTheAmount, realTimeAmount) == 0) {
            try {
                if (judgeTime(bankName)) {//屏蔽时间内  不上报待确认
                    statusCode = "1";
                } else {
                    statusCode = "4";
                }
            } catch (ParseException e) {
                LogToFile.d(bankName, "时间判定错误 ===" + e.getMessage());
                statusCode = "1";
            }
        } else if (sub(Double.toString(sub(saveTheAmount, realTimeAmount)), orderAmount) == 0) {
            statusCode = "0";
        } else {
            statusCode = "1";
        }
        LogToFile.d(bankName, "查账---余额变化后状态码 ===" + statusCode);
        return statusCode;
    }

    /**
     * double 相减
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double sub(String d1, String d2) {
        BigDecimal bd1 = new BigDecimal(d1);
        BigDecimal bd2 = new BigDecimal(d2);
        return bd1.subtract(bd2).doubleValue();
    }

    /**
     * 判定屏蔽时间
     *
     * @param bankName
     * @return
     * @throws ParseException
     */
    public static boolean judgeTime(String bankName) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
        Date nowTime = df.parse(df.format(new Date()));
        Date startTime = df.parse("00:00");
        Date endTime = df.parse("4:59");
        //设置当前时间
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        //设置开始时间
        Calendar startBegin = Calendar.getInstance();
        startBegin.setTime(startTime);//上午开始时间
        Calendar endBegin = Calendar.getInstance();
        endBegin.setTime(endTime);
        LogToFile.d(bankName, "---------------------" + nowTime.toString());
        if (date.after(startBegin) && date.before(endBegin)) {
            LogToFile.d(bankName, "在屏蔽时间内");
            return true;
        } else {
            LogToFile.d(bankName, "非屏蔽时间内");
            return false;
        }
    }
}
